#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
设置管理员系统和权限控制
"""

import sys
import os
from sqlalchemy.orm import Session
from passlib.context import CryptContext

# 添加backend目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

from app.core.database import SessionLocal, engine
from app.models.user import User

# 密码上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def setup_admin_system():
    """设置管理员系统和权限控制"""
    db = SessionLocal()
    try:
        # 1. 检查并设置admin密码为123456
        admin = db.query(User).filter(User.username == 'admin').first()
        if admin:
            # 强制设置admin密码为123456
            admin.hashed_password = get_password_hash('123456')
            admin.is_superuser = True  # 确保admin是超级用户
            print("✅ admin密码已设置为: 123456")
        else:
            # 创建admin用户
            admin = User(
                username='admin',
                email='admin@example.com',
                full_name='系统管理员',
                hashed_password=get_password_hash('123456'),
                is_superuser=True,
                is_active=True
            )
            db.add(admin)
            print("✅ admin用户已创建，密码: 123456")
        
        # 2. 确保只有admin是超级用户
        all_users = db.query(User).all()
        superuser_count = 0
        for user in all_users:
            if user.username != 'admin' and user.is_superuser:
                user.is_superuser = False
                superuser_count += 1
        
        if superuser_count > 0:
            print(f"✅ 已撤销 {superuser_count} 个非admin用户的超级用户权限")
        
        # 3. 确保所有普通用户只能访问考勤管理
        # 这个权限控制将在前端实现
        
        db.commit()
        
        # 4. 验证设置
        admin = db.query(User).filter(User.username == 'admin').first()
        password_correct = verify_password('123456', admin.hashed_password)
        
        print(f"\n📋 权限验证结果:")
        print(f"   admin密码正确: {password_correct}")
        print(f"   admin超级用户: {admin.is_superuser}")
        
        # 检查超级用户总数
        superusers = db.query(User).filter(User.is_superuser == True).all()
        print(f"   超级用户总数: {len(superusers)}")
        for su in superusers:
            print(f"   - {su.username} ({'✅ admin' if su.username == 'admin' else '❌ 非admin'})")
        
        # 普通用户列表
        regular_users = db.query(User).filter(User.is_superuser == False).all()
        print(f"\n👥 普通用户 ({len(regular_users)}个):")
        for user in regular_users:
            print(f"   - {user.username} (只能访问考勤管理)")
            
    except Exception as e:
        print(f"❌ 设置管理员系统时出错: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    setup_admin_system()